﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using MAPI = Microsoft.Office.Interop.Outlook;
using System.Data.SqlServerCe;
using Sandkeeper.SandkeeperDataSetTableAdapters;


namespace Sandkeeper.CustomWindows
{
    public partial class TimerMainForm : Form
    {
        private DateTime StartTime;
        private bool TimerStarted = false;
        private MAPI.TaskItem activeTask;

        public MAPI.TaskItem ActiveTask
        {
            get { return activeTask;  }
            set
            {
                activeTask = value;
                Text = activeTask.Subject;
            }
        }

        public TimerMainForm()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStop.Enabled = true;
            btnStart.Enabled = false;
            if (!TimerStarted)
                StartTime = DateTime.Now;
            TimerStarted = true;
            SandKeeperTimer.Start();

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            DateTime EndTime = DateTime.Now;
            TimeSpan timePassed = EndTime.Subtract(StartTime);            

            btnStop.Enabled = false;
            btnStart.Enabled = true;
            SandKeeperTimer.Stop();
            // Outlook stores TotalWork in minutes.            
            int workDoneInSession = (timePassed.Hours * 60) + timePassed.Minutes+ ( timePassed.Seconds>0?1:0);
            if (workDoneInSession > 0)
            {
                // Update and save task
                activeTask.TotalWork += workDoneInSession;
                activeTask.Save();
                // Update the history database
                HistoryTableAdapter history = new HistoryTableAdapter();
                history.Insert(activeTask.EntryID, activeTask.Subject, StartTime, EndTime, workDoneInSession);
            }
        }

        private void SandKeeperTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan timePassed = DateTime.Now.Subtract(StartTime);            
            lbTimeElapsed.Text =    string.Format("{0:00}",timePassed.Hours) + ":" + 
                                    string.Format("{0:00}",timePassed.Minutes)+ ":" + 
                                    string.Format("{0:00}",timePassed.Seconds );

        }
    }
}
